<template>
    <div>
        <div class="main-head flex-between container-fluid">
            <div class="title">
                <h1 v-text="$t('pro.viewFilterList.viewFilterListName')"></h1>
            </div>
        </div>
        <div class="content container-fluid">
            <div class="breadcrumb">
                <a-breadcrumb :routes="routes">
                    <template slot="itemRender" slot-scope="{route, params, routes}">
                        <span v-if="routes.indexOf(route) === routes.length - 1">
                            {{route.breadcrumbName}}
                        </span>
                        <router-link v-else :to="`${route.path}`">
                            {{route.breadcrumbName}}
                        </router-link>
                    </template>
                </a-breadcrumb>
            </div>
            <div class="portlet">
                <div class="tools filter-list-tools flex-between">
                    <div class="tools-l">
                        <nav class="nav flex-between">
                            <a v-for="(li,key) in textareaPlaceholder"
                               :key="key"
                               @click="selectList(key)"
                               :class="{'active':selectedList === key}">
                                {{li.label}}({{dataNumber[key] || 0}})
                            </a>
                        </nav>
                    </div>
                    <div class="tools-r flex-between">
                        <a-button type="primary" icon="plus" @click="handleAdd" v-text="$t('pro.viewFilterList.addList')">
                        </a-button>
                        <a-button type="primary" icon="delete" @click="handleClearList" v-text="$t('pro.viewFilterList.clearList')">
                        </a-button>
                        <!--<a-input-search :placeholder="$t('pro.viewFilterList.searchList')"  @search="onSearch" style="width:200px; " />-->
                        <a-dropdown-button @click="handleExportClick()">
                            {{$t('pro.viewFilterList.downloadAll')}}
                            <a-menu slot="overlay">
                                <a-menu-item v-for="(li,key) in textareaPlaceholder" :key="key"  @click="handleExportClick(key)">
                                    {{li.label}}
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown-button>
                    </div>
                </div>
                <a-spin :spinning="refresh" tip="loading...">
                    <div :class="{'filter-list-view': !empty}">
                        <template v-if="empty">
                            <p class="empty" v-text="$t('pro.viewFilterList.emptyList')"></p>
                        </template>
                        <a-row v-else>
                            <template v-if="!checked">
                                <a-col v-show="fiterList.length > 0"  v-for="(li,index) in fiterList"
                                       :key="index+'key'" :span="4" :xs="12" :sm="8" :md="6" :lg="4">
                                    <div class="filter-list-item" :class='listItem'>
                                        <div class="value" :class="li.class">
                                            {{li.value}}
                                        </div>
                                        <div class="delete">
                                            <a-icon :type="li.type" @click="handleSelect(index,li.check)" />
                                        </div>
                                    </div>
                                </a-col>
                            </template>
                            <template v-if="checked">
                                <a-col v-for="(li,index) in showDeleteList"
                                       :key="index+'key'" :span="4" :xs="12" :sm="8" :md="6" :lg="4">
                                    <div class="filter-list-item" :class='listItem'>
                                        <div class="value" :class="li.class">
                                            {{li.value}}
                                        </div>
                                        <div class="delete">
                                            <a-icon :type="li.type" @click="handleSelect(index,li.check)" />
                                        </div>
                                    </div>
                                </a-col>
                            </template>
                        </a-row>
                        <!--删除及选中按钮模块-->
                        <div v-show="btnShow">
                            <a-button class="button" type="primary" @click="handleDeleteSelected" v-text="$t('pro.viewFilterList.deleteSelected')">
                            </a-button>
                            <a-button class="button" type="primary" @click="handleUncheck()" v-text="$t('pro.viewFilterList.deselectAll')">
                            </a-button>
                            <a-button class="button" type="primary" @click="handleShowDel()">
                                <a-checkbox @change="handleShowDelCheck" :checked="checked"/>
                                {{$t('pro.viewFilterList.showSelected')}}
                            </a-button>
                            <!--<a-checkbox @change="handleShowDel2">Checkbox</a-checkbox>-->
                        </div>
                    </div>
                    <a-pagination
                        v-show="pagination.total > 0"
                        style="text-align: right"
                        :pageSize="pagination.size"
                        :pageSizeOptions="pageSizeOptions"
                        showQuickJumper
                        showSizeChanger
                        @showSizeChange="handlePageChange"
                        :total="pagination.total"
                        v-model="pagination.current"
                        @change="handlePageChange">
                    </a-pagination>
                </a-spin>
            </div>
        </div>
        <!--添加数据的弹出框-->
        <a-modal
            :title="$t('pro.viewFilterList.addModelTitle') + ` ${listName}`"
            v-model="modalVisible"
            :afterClose="handleClose"
            :footer="null">
            <a-form layout='vertical' :form="form" @submit="handleSubmit">
                <a-form-item
                    :validate-status="validateStatus"
                    :help="errorMsg"
                >
                    <a-input
                        :disabled="loading"
                        :rows="6"
                        :placeholder="placeholder"
                        type='textarea'
                        v-decorator="[
                           selectedList,
                            {
                                rules: [{
                                    required: true,
                                    message: $t('pro.viewFilterList.checkMessage') + listName + '!'
                                },{
                                    whitespace: true,
                                    message: $t('pro.viewFilterList.emptyMess')
                                }],
                            }
                        ]"
                    />
                </a-form-item>
                <a-form-item>
                    <a-button
                        style="float: right"
                        type="primary"
                        html-type="submit"
                        :loading="loading"
                        v-text="$t('pro.public.buttonSave')"
                    >
                    </a-button>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>
<script>
    import {getAllDataByPage, getDelete, getAddData, getEmptyData, getDownload} from "@/api/lists";
    import {getDataByPageID} from "@/api/filter-list";
    import {Clearempty} from "@/utils/arr";
    import {download} from "@/utils/downLoad";
    import {validURL,validIP,validID,validDevice_ID} from "@/utils/validate";


    export default {
        data() {
            return {
                form: this.$form.createForm(this),
                validateStatus: 'success',
                errorMsg: '',
                refresh: true,  //页面刷新的动画
                loading: false, //是否加载
                addListVal: "", //添加的数据
                checked: false, //显示选中按钮
                btnShow: false, //控制按钮显示
                fiterList: [],  //默认展示的列表
                delList: [],    //需要删除的数据文本数组
                showDeleteList: [],//展示的删除列表
                dataNumber:{},  //列表数据数量
                pageSizeOptions:["30","60","90","120"],
                selectedList: "domains",//默认为domains
                modalVisible: false,
                empty: false,
                pagination: {
                    size: 30,   //默认条数
                    current: 1, //当前页
                }, //分页器
            };
        },
        methods: {
            getRetresh(params = {},name) {
                this.refresh = true
                params.page = this.pagination.current || 1
                params.results = this.pagination.size || 30
                getDataByPageID(this.filterListId).then(res => {//通过id获取过滤器列表单条数据
                    if (res.data.code == 200){
                        let keys = Object.keys(res.data.data)
                        let textareaPlaceholder = Object.keys(this.textareaPlaceholder)
                        for (let i = 0;textareaPlaceholder.length > i;i++ ) {
                            for (let j = 0;keys.length >j;j++ ) {
                                if(textareaPlaceholder[i] == keys[j]){
                                    this.dataNumber[keys[j]] = res.data.data[keys[j]]
                                }
                            }
                        }
                    }
                }).catch(err =>{
                    console.log(err);
                })
                getAllDataByPage({
                    filterListId: this.filterListId,
                    name: name,
                    ...params
                }).then(res => {
                    if (res.data.code == 200) {//成功执行
                    this.empty = false;
                    let data = res.data.data
                    // let text = data.text;
                        //拿到返回的数据
                        // let arr = (text.slice(1, text.length - 1)).split(",")
                        let arr=data.text;
                        let list = arr.map(item => {
                            //去除子元素中的空格
                            return item.trim().replace(/\s/g, "")
                        })
                        Clearempty(list);//清除空的元素
                        this.pagination.total = data.filesize//数据总数
                        this.fiterList = list;//处理好的数据给到要渲染的数组
                        this.fiterList = this.fiterList.map(item => {//进行重构
                            return {value: item, type: 'close-circle', class: 'nonetext', check: false}
                        })
                    }else {
                        this.empty = true
                        this.fiterList = [];//渲染数组为空
                        this.pagination.total = 0
                    }
                }).finally(() => {
                    this.refresh = false //停止加载动画
                })
            },
            //切换展示项
            selectList(selectedList) {
                this.selectedList = selectedList;
                this.getRetresh({
                    results: this.pagination.size, //分页展示的数量
                    page: this.pagination.current,  //当前页
                },this.selectedList)
            },
            //改变页数的事件
            handlePageChange(page, pageSize){
                this.pagination.size = pageSize
                this.pagination.current = page
                this.btnShow = false
                this.getRetresh({
                    results: this.pagination.size, //分页展示的数量
                    page: this.pagination.current,  //当前页
                },this.selectedList)
            },
            //点击出现添加数据的弹框
            handleAdd() {
                this.modalVisible = true;
            },
            //关闭添加数据的弹框事件
            handleClose(){
                this.form.resetFields(); //重置输入文本
                this.validateStatus = "success";
                this.errorMsg = ""
            },
            /***
             * 点击选中
             * @param index 数据的在过滤器列表的索引
             * @param check 该数据是否为选中状态
             */
            handleSelect(index, check) {
                this.fiterList[index].check = !this.fiterList[index].check;//修改状态
                check = this.fiterList[index].check
                if (check) {//判断这条数据是否是未选中状态
                    this.fiterList[index].type = 'reload'//更改图标
                    this.fiterList[index].class = 'deltext'//增加删除线
                    this.delList.push(this.fiterList[index].value)//将该条数据的值添加到需要删除的数据数组
                } else {
                    this.fiterList[index].type = 'close-circle'
                    this.fiterList[index].class = 'nonetext'
                    let fiter = this.fiterList[index].value
                    this.delList.splice(this.delList.indexOf(fiter),1)//将该条数据的值从需要删除的数据数组删除
                }
                if (this.delList.length == 0){//判断删除数组中是否有数据
                    this.btnShow = false//将按钮模块隐藏
                }else {
                    this.btnShow = true//将按钮模块显示
                }
            },
            //展示选中的删除项(多选框的change事件)
            handleShowDelCheck(){
                if (this.checked) {
                    //筛选出被选中要删除的数据
                    this.showDeleteList = this.fiterList.filter(item => {
                        return item.type === 'reload'
                    })
                }
            },
            //展示选中的删除项
            handleShowDel() {
                this.checked = !this.checked;//更改该按钮的选中状态
                if (this.checked) {
                    //筛选出被选中要删除的数据
                    this.showDeleteList = this.fiterList.filter(item => {
                        return item.type === 'reload'
                    })
                }
            },
            //取消选中的删除按钮事件
            handleUncheck() {
                this.checked = false
                this.fiterList = this.fiterList.filter(item => {
                    item.check = false,//清空所有的选中状态
                    item.type = 'close-circle'
                    item.class = 'nonetext'
                    return item
                })
                this.delList = [];//清空删除列表
                this.btnShow = !this.btnShow;//隐藏按钮
            },
            //删除选中的数据
            handleDeleteSelected() {
                let that = this
                this.$confirm({
                    title: this.$t('pro.viewFilterList.deleteModelTitle'),
                    okText: this.$t('pro.public.buttonYes'),
                    okType: "danger",
                    cancelText: this.$t('pro.public.buttonNo'),
                    onOk: () => {
                        getDelete({
                            filterList: that.delList,
                            filterListId: that.filterListId,
                            name: that.selectedList
                        }).then(res => {
                            if (res.data.code == 200) {//判断是否成功执行
                                that.getRetresh({
                                    results: that.pagination.size, //分页展示的数量
                                    page: that.pagination.current,  //当前页
                                }, that.selectedList);//刷新
                                that.btnShow = !that.btnShow;//隐藏按钮
                                that.checked = false
                                that.delList = []//清空删除列表
                                //无需调用api，界面数据刷新即可
                                that.$message.success(this.$t('pro.viewFilterList.delete_Success'))
                            }
                        }).catch(() => {
                            that.$message.error(this.$t('pro.viewFilterList.delete_Error'))
                        })
                    },
                    onCancel() {//取消删除
                        return
                    }
                });
            },
            //下载数据
            handleExportClick(name) {
                const parameter = {
                    filterListId: this.filterListId,
                    name: name
                }
                getDownload(parameter)
                    .then(res => {
                        //let {code,data} = res.data
                        download(res.data)
                        this.$message.success(this.$t('pro.viewFilterList.download_Success'))
                    })
                    .catch(() => {
                        this.$message.success(this.$t('pro.viewFilterList.download_Error'))
                    })
            },
            //搜索对应的数据项
            onSearch(value) {//待完成
                this.getRetresh({
                    results: this.pagination.size, //分页展示的数量
                    page: this.pagination.current,  //当前页
                    //模糊查询字段
                }, this.selectedList)
            },
            //添加数据的提交事件
            handleSubmit  (e) {
                let that = this;
                e.preventDefault();
                this.form.validateFields((err, values) => {
                    if (!err) {
                        that.addListVal = Object.values(values).toString();
                        let textCheck = that.addListVal.split(/[\n,]/g);
                        let addCheck = textCheck.every(function (item) {
                            //判断数据格式
                            if (that.selectedList == "domains") {
                                return validURL(item)
                            } else if(that.selectedList == "ips") {
                                return validIP(item)
                            }else if(that.selectedList == "deviceIfas"){
                                return validDevice_ID(item)
                            }else {
                                return validID(item)
                            }
                        });
                        this.loading = !this.loading; //开启加载动画组件
                        let addList = new Object();

                        Object.keys(values).forEach(key => {
                            addList[key] = values[key];
                            addList['filterListId'] = that.filterListId;
                        });
                        if (addCheck){//校验成功再添加
                            getAddData(addList).then(res => {
                                if (res.data.code == 200) {
                                    this.$message.success(this.$t('pro.viewFilterList.add_Success'));
                                    setTimeout(() =>{
                                        this.loading = false;//关闭加载动画组件
                                        this.modalVisible = false;//关闭输入框
                                        this.addListVal = "";//清空输入文本
                                        this.form.resetFields();//重置输入文本
                                        this.getRetresh({
                                            results: this.pagination.size, //分页展示的数量
                                            page: this.pagination.current,  //当前页
                                        }, this.selectedList);//刷新
                                    },1000)
                                }
                            }).catch(() => {
                                this.$message.error(this.$t('pro.viewFilterList.add_Error'));
                            }).finally(() => {
                                this.loading = false;
                                this.modalVisible = false;
                            })
                        } else{
                            this.validateStatus = "error";
                            this.errorMsg = this.$t('pro.viewFilterList.errorMeg');
                            this.loading = !this.loading;//关闭加载动画组件
                        }
                    }
                });
            },
            //清空列表
            handleClearList() {
                let that = this
                this.$confirm({
                    title: this.$t('pro.viewFilterList.clearModelTitle'),
                    content: this.$t('pro.viewFilterList.clearModelContent')  +`${this.listName}`,
                    okText: this.$t('pro.public.buttonYes'),
                    okType: "danger",
                    cancelText: this.$t('pro.public.buttonNo'),
                    onOk: () => {
                        getEmptyData({
                            filterListId: that.filterListId,
                            name: that.selectedList
                        }).then(res => {
                            if (res.data.code == 200){
                                that.$message.success(this.$t('pro.viewFilterList.clearList_Success'));
                                setTimeout(()=>{
                                    that.btnShow = false
                                    that.pagination.total = 0;//清空分页器总数量
                                    that.getRetresh({
                                        results: that.pagination.size, //分页展示的数量
                                        page: that.pagination.current,  //当前页
                                    },that.selectedList)//刷新
                                },1000)
                            }
                        }).catch(err => {
                            that.$message.error(this.$t('pro.viewFilterList.clearList_Error'));
                        })
                    }
                });
            }
        },
        created() {
            this.routes[1].breadcrumbName = this.filterListName;
            this.getRetresh({
                results: this.pagination.size, //分页展示的数量
                page: this.pagination.current,  //当前页
            },"domains");//默认显示domains
        },
        computed: {
            routes(){
                const router = [
                    {
                        path: "/bidder/filterlist",
                        breadcrumbName: this.$t('pro.public.header.FilterList')
                    },
                    {
                        path: "first",
                        breadcrumbName: this.$t('pro.viewFilterList.listName')
                    }
                ]
                return router
            },
            listItem(){
                return this.selectedList == "deviceIfas" ? 'deviceid' : 'orther'
            },
            filterListId() {
                return this.$route.query.id;
            },
            filterListName(){
                return this.$route.query.listName;
            },
            list() {
                return Object.entries(this.textareaPlaceholder).map(item =>{
                    return {
                        title: item[1].label,
                        key: item[0]
                    };
                })
            },
            listName() {
                const findTitle = this.list.find(item => item.key === this.selectedList);
                return findTitle.title;
            },
            placeholder() {
                let that = this
                const findPlaceholder = Object.keys(this.textareaPlaceholder).find(function (item) {
                    return item === that.selectedList
                })
                return this.textareaPlaceholder[findPlaceholder].placeholder;
            },
            textareaPlaceholder() {
                return this.$t('pro.textareaPlaceholder')
            }
        },
    };
</script>

<style scoped>
    .flex-between:not(.filter-list-tools) > *:not(:last-child) {
        margin-right: 20px;
    }
</style>

<style lang="less">
    .deltext {
        text-decoration: line-through;
    }

    .nonetext {
        text-decoration: none;
    }

    .button {
        margin-right: 0.5rem;
        margin-top: 0.5rem;
    }
    .portlet .deviceid{
        width: 90%;
    }
    portlet .orther{
        width: 100%;
    }
    @media screen and (max-width: 1450px) {
        .filter-list-tools {
            display: block;
            .nav {
                flex-wrap: wrap;
                justify-content: flex-start;
            }
            .tools-l {
                margin-bottom: 15px;
            }
            .tools-r {
                justify-content: flex-end;
            }
        }
    }

    @media screen and (max-width: 768px) {
        .filter-list-tools {
            border-bottom: none;
            .tools-l {
                border-bottom: 1px solid #d9d9d9;
            }
            .tools-r {
                display: grid;
                grid-gap: 15px;
            }
            .tools-r.flex-between:not(.filter-list-tools) > *:not(:last-child) {
                margin-right: 0;
            }
        }
    }

    // 列表容器
    .filter-list-view {
        padding: 15px 0;
    }

    .filter-list-grid {
        grid-template-columns: repeat(6, 1fr);
    }

    @media screen and (max-width: 1650px) {
        .filter-list-grid {
            grid-template-columns: repeat(5, 1fr);
        }
    }

    @media screen and (max-width: 1450px) {
        .filter-list-grid {
            grid-template-columns: repeat(4, 1fr);
        }
    }

    @media screen and (max-width: 1150px) {
        .filter-list-grid {
            grid-template-columns: repeat(3, 1fr);
        }
    }

    @media screen and (max-width: 992px) {
        .filter-list-grid {
            grid-template-columns: repeat(2, 1fr);
        }
    }

    @media screen and (max-width: 640px) {
        .filter-list-grid {
            grid-template-columns: repeat(1, 1fr);
        }
    }

    // 单个列表
    .filter-list-item {
        grid-gap: 0;
        grid-template-columns: 1fr 10px;
        width: 100%;
        overflow: hidden;
        padding: 5px 5px;
        .value,
        .delete {
            grid-row: 1;
        }
        .value {
            grid-column: 1;
        }
        .delete {
            right: 10px;
            top: 5px;
            width: 100%;
            position: absolute;
            grid-column: 2;
            text-align: right;
            padding: 0 5px;
            cursor: pointer;
        }
    }

    .delete {
        transform: scale(0);
        transition: all 0.2s ease-in;
    }

    .filter-list-item:hover {
        position: relative;
        background-color:rgb(239, 243, 248);
        &::after {
            content: "";
            display: block;
            width: 100%;
            height: 1px;
            background-color: rgba(217, 217, 217, 0.6);
            position: absolute;
            bottom: 0;
            left: 0;
        }
        .delete {
            transform: scale(1);
        }
    }
</style>
